import {
  _decorator,
  Component,
  Node,
  Collider2D,
  Contact2DType,
  IPhysics2DContact,
  RigidBody2D,
} from "cc";
const { ccclass, property } = _decorator;
import { GameManager } from "./Manager/GameManager";
import DataManager from "./Runtime/DataManager";
@ccclass("BaseReward")
export class BaseReward extends Component {
  @property
  speed: number = 80;

  protected collider: Collider2D = null;

  @property({ tooltip: "触发吸附的临界距离（像素）" })
  attractRadius: number = 200;

  @property({ tooltip: "最大吸附速度（像素/秒）" })
  attractSpeed: number = 800;

  private player: Node = null;

  start() {
    // 注册碰撞体的回调函数
    this.collider = this.getComponent(Collider2D);
    if (this.collider) {
      this.collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
      this.collider.on(Contact2DType.END_CONTACT, this.onEndContact, this);
    }
    // 获取GameManager实例中的player属性
    this.player = DataManager.Instance.player;
  }

  onDestroy() {}
  beforeDestroy() {
    // 取消注册碰撞回调
    if (this.collider) {
      this.collider.off(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
      this.collider.off(Contact2DType.END_CONTACT, this.onEndContact, this);
      this.collider.enabled = false;
    }
  }
  update(deltaTime: number) {
    // 基础的向下移动逻辑
    const p = this.node.position;

    // 如果有玩家对象，检查是否需要吸附
    if (this.player) {
      const playerPos = this.player.position;
      const dx = playerPos.x - p.x;
      const dy = playerPos.y - p.y;
      const distance = Math.sqrt(dx * dx + dy * dy);

      // 当距离小于吸附半径时，开始吸附
      if (distance < this.attractRadius) {
        // 计算方向向量并归一化
        const dirX = dx / distance;
        const dirY = dy / distance;

        // 根据距离动态调整速度，距离越近速度越快
        const speedFactor = 1 - distance / this.attractRadius;
        const currentSpeed = this.attractSpeed * speedFactor;

        // 更新位置
        this.node.setPosition(
          p.x + dirX * currentSpeed * deltaTime,
          p.y + dirY * currentSpeed * deltaTime,
          p.z
        );
        return; // 吸附时不执行基础移动
      }
    }

    // 基础移动逻辑
    this.node.setPosition(p.x, p.y - this.speed * deltaTime, p.z);

    // 超出屏幕范围销毁
    if (this.node.position.y < -380) {
      this.node.destroy();
    }
  }

  protected onBeginContact(
    selfCollider: Collider2D,
    otherCollider: Collider2D,
    contact: IPhysics2DContact | null
  ) {
    console.log("父类onBeginContact");

    // 子类重写此方法实现具体的碰撞逻辑
  }
  protected onEndContact(
    selfCollider: Collider2D,
    otherCollider: Collider2D,
    contact: IPhysics2DContact | null
  ) {
    // 子类重写此方法实现具体的碰撞结束逻辑
    this.scheduleOnce(function () {
      this.node.destroy();
    }, 0);
  }
}
